import React from "react";
import { Toast, ImagePicker } from "antd-mobile";
import { Upload } from "antd";
import BenzAMRRecorder from "benz-amr-recorder";

var amr = new BenzAMRRecorder();

export default class Index extends React.Component {
  constructor(props) {
    super(props);
    var type = props.match.params.type;
    this.state = {
      files: [],
      multiple: false,
      content: "",
      is_show: 0,
      type: type,
      status: 0,
    };
  }
  componentDidMount() {
    document.title = "发布";
    global.Ajax.hhtc_request("user/get_qiniu_token", {}).then((data) => {
      if (data.code === 1) {
        this.setState(data.data);
      }
    });
  }
  // onChange = (files, type, index) => {
  //     console.log(files, type, index);
  //     this.setState({
  //       files,
  //     });
  // }
  // 删除
  del(index) {
    var files = this.state.files;
    files.splice(index, 1);
    this.setState({
      files: files,
    });
  }
  // 发布帖子
  sub() {
    if (this.state.content === "") {
      return Toast.fail("请输入内容", 1);
    }
    Toast.loading();
    var req = {
      content: this.state.content,
      imgs: this.state.files,
      type: this.state.type,
      status: this.state.status,
    };
    global.Ajax.hhtc_request("dynamic/fabutie", req).then((data) => {
      Toast.hide();
      if (data.code === 1) {
        Toast.success(data.msg, 1, () => {
          this.props.history.goBack();
        });
      } else {
        Toast.fail(data.msg, 1);
      }
    });
  }

  // 点击播放按钮
  playVoice(url) {
    amr = new BenzAMRRecorder();
    var iconFlag = !this.state.iconFlag; // 这个变量是控制播放与否的
    var that = this;
    amr.initWithUrl(url).then(function () {
      amr.play();
      that.setState({
        iconFlag: iconFlag,
      });
    });
    // 监听播放完成
    amr.onEnded(() => {
      this.setState({
        iconFlag: false,
      });
    });
  }
  paused() {
    var iconFlag = !this.state.iconFlag; // 这个变量是控制播放与否的
    console.log("iconFlag: ", iconFlag);
    amr.stop();
    this.setState({
      iconFlag: iconFlag,
    });
  }

  render() {
    var that = this;
    const props = {
      name: "file",
      action: "https://up.qiniup.com",
      showUploadList: false,
      headers: {
        authorization: "authorization-text",
      },
      data: (file) => {
        console.log(file);

        this.setState({
          is_show: 1,
        });
        //
        var binaryData = [];
        // 传入file
        binaryData.push(file);
        //获取视频或者音频时长
        var fileurl = URL.createObjectURL(
          new Blob(binaryData, { type: "application/zip" })
        );

        var audioElement = new Audio(fileurl);
        var duration;
        audioElement.addEventListener("loadedmetadata", function (_event) {
          duration = audioElement.duration;


          if(duration > 15) {

            that.setState({
              status: 1,
              
            });
          }
          console.log("视频的时长为:", that.state.status); //单位：秒
          
          
        });
        


        //
        var houzui = "." + file.name.split(".")[1];
        
        return {
          token: that.state.upload_token,
          key:
            Date.now() +
            Math.floor(Math.random() * (999999 - 100000) + 100000) +
            "1" +
            houzui,
        };
      },
      onChange(info) {
        console.log(info);
        if (info.file.status === "done") {
          var src = that.state.domain + "/" + info.file.response.key;
          var files = that.state.files;
          files.push(src);
          that.setState({
            files: files,
            is_show: 0,
          });
        } else if (info.file.status === "error") {
          Toast.fail(info.file.response.error);
        }
      },
    };
    return (
      <div
        className=''
        style={{ paddingBottom: 70, minHeight: "100vh", background: "#F7F7F7" }}
      >
        {this.state.is_show == 1 && (
          <div
            style={{
              width: "100%",
              height: document.body.clientHeight,
              position: "absolute",
              display: "flex",
              flexDirection: "column",
              alignItems: "center",
              justifyContent: "center",
              backgroundColor: "rgba(0,0,0,0.5)",
            }}
          >
            <img alt='' src={require("../../imgs/loading.gif")} />
            <p style={{ color: "#fff", fontSize: "16px", marginTop: "10px" }}>
              上传中...
            </p>
          </div>
        )}
        <div style={{ background: "#fff", paddingBottom: "1vw" }}>
          <textarea
            className='sq_release'
            placeholder='分享开心事~'
            onChange={(e) => {
              this.setState({
                content: e.target.value,
              });
            }}
          ></textarea>
          <div className='rele_imglist'>
            {this.state.files.map((item, index) => {
              if (this.state.type == 2) {
                if (item.indexOf(".amr")) {
                  return (
                    <div key={"img" + index}>
                      <button
                        onClick={
                          this.state.iconFlag
                            ? this.paused.bind(this)
                            : this.playVoice.bind(this, item)
                        }
                        style={{
                          border: "none",
                          width: "10vw",
                          backgroundColor: "#ccc",
                          color: "#fff",
                          borderRadius: "10px",
                          height: "5vw",
                          marginBottom: 10,
                        }}
                      >
                        {this.state.iconFlag ? "暂停" : "播放"}
                      </button>
                    </div>
                  );
                } else {
                  return (
                    <div key={"img" + index}>
                      <audio
                        autoplay
                        controls
                        src={item}
                        style={{
                          display: "block",
                          width: "22.4vw",
                          height: "22.4vw",
                        }}
                      ></audio>
                      <img
                        alt=''
                        src={require("../../imgs/close1.png")}
                        className='icon1'
                        onClick={this.del.bind(this, index)}
                      />
                    </div>
                  );
                }
              } else if (this.state.type == 3||this.state.type == 4) {
                return (
                  <div key={"img" + index}>
                    <video
                      controls
                      src={item}
                      style={{
                        display: "block",
                        width: "22.4vw",
                        height: "22.4vw",
                      }}
                    ></video>
                    <img
                      alt=''
                      src={require("../../imgs/close1.png")}
                      className='icon1'
                      onClick={this.del.bind(this, index)}
                    />
                  </div>
                );
              } else {
                return (
                  <div key={"img" + index}>
                    <img
                      alt=''
                      src={item}
                      style={{
                        display: "block",
                        width: "22.4vw",
                        height: "22.4vw",
                      }}
                    />
                    <img
                      alt=''
                      src={require("../../imgs/close1.png")}
                      className='icon1'
                      onClick={this.del.bind(this, index)}
                    />
                  </div>
                );
              }
            }, this)}
            {this.state.files.length !== 4 && (
              <div>
                <Upload {...props}>
                  <div>
                    <img
                      alt=''
                      src={require("../../imgs/add1.png")}
                      style={{ width: "22.4vw" }}
                    />
                  </div>
                </Upload>
              </div>
            )}
          </div>

          {/* <ImagePicker
                        files={this.state.files}
                        onChange={this.onChange}
                        onImageClick={(index, fs) => console.log(index, fs)}
                        selectable={this.state.files.length < 7}
                        multiple={this.state.multiple}
                    /> */}
        </div>
        <p className='sq_sub' onClick={this.sub.bind(this)}>
          发布
        </p>
      </div>
    );
  }
}
